var map;
var showMarker = true;
var lengthPoly = 50;
var poly = [];
var path = [];
var markers = [];
var positions = [];
for(var i = 0; i<=lengthPoly;i++){
	poly.push(new google.maps.Polygon({
			strokeWeight: 3,
			editable:true,
			fillColor: 'green',
			fillOpacity: 0.4,
			strokeColor: 'red',
			strokeOpacity: 1,
			strokeWeight: 3,
			zIndex: 1
		}));
	path.push(new google.maps.MVCArray);
	positions.push([]);
	markers.push([]);
}
var positionsMVC = [];
var markerBounds = new google.maps.LatLngBounds();
var objMap = {
	zoom: 15,
	center:new google.maps.LatLng(0, 0),
	lat:-34.424983999999990000,
	lng:150.893123899999980000
};
objMap.center = new google.maps.LatLng(objMap.lat, objMap.lng);
var index = 0;
path[index] = new google.maps.MVCArray;
positions[index] = [];
var multiple = false;
var dragMarkerStart;

function resetMap(){
	
	dragMarkerStart;
	showMarker = true;
	poly = [];
	path = [];
	markers = [];
	positions = [];
	for(var i = 0; i<=lengthPoly;i++){
		poly.push(new google.maps.Polygon({
				strokeWeight: 3,
				editable:true,
				fillColor: 'green',
				fillOpacity: 0.4,
				strokeColor: 'red',
				strokeOpacity: 1,
				strokeWeight: 3,
				zIndex: 1
			}));
		path.push(new google.maps.MVCArray);
		positions.push([]);
		markers.push([]);
	}
	positionsMVC = [];
	markerBounds = new google.maps.LatLngBounds();
	objMap = {
		zoom: 15,
		center:new google.maps.LatLng(0, 0),
		lat:-34.424983999999990000,
		lng:150.893123899999980000
	};
	objMap.center = new google.maps.LatLng(objMap.lat, objMap.lng);
	index = 0;
	path[index] = new google.maps.MVCArray;
	positions[index] = [];
	multiple = false;
	
	
	poly[index] = new google.maps.Polygon({
		strokeWeight: 3,
		editable:true,
		fillColor: 'green',
		fillOpacity: 0.4,
		strokeColor: 'red',
		strokeOpacity: 1,
		strokeWeight: 3,
		zIndex: 1
	});
	poly[index].setMap(map);
	

	poly[index].setPaths(new google.maps.MVCArray([path[index]]));
	
}





/**
	Start function for gmap.
**/

function initialize() {
    map = new google.maps.Map(document.getElementById("map-canvas"), {
        zoom: objMap.zoom,
        center: objMap.center,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
	if(!multiple){
		poly[index] = new google.maps.Polygon({
			strokeWeight: 3,
			editable:true,
			fillColor: 'green',
			fillOpacity: 0.4,
			strokeColor: 'red',
			strokeOpacity: 1,
			strokeWeight: 3,
			zIndex: 1
		});
		poly[index].setMap(map);
		

		poly[index].setPaths(new google.maps.MVCArray([path[index]]));

	}else{

		$.each(path,function(x,y){
			
			if(y.length != 0 && typeof y.length == "number"){
				
				poly[x] = new google.maps.Polygon({
					strokeWeight: 3,
					editable:false,
					fillColor: 'green',
					fillOpacity: 0.4,
					strokeColor: 'red',
					strokeOpacity: 1,
					strokeWeight: 3,
					zIndex: 1
				});
				poly[x].setMap(map);
				

				poly[x].setPaths(new google.maps.MVCArray([path[x]]));
				
				
			}
			
		});
		
		
		
		
	}
	google.maps.event.addListener(map, 'click', function(event){
		addPoint(event,false);
	});

	
	
	
	
	autocompleteBox();
	
	if(multiple){
		
		$.each(markers,function(x,y){
			if(y.length != 0 && typeof y.length == "number"){
				$.each(y,function(xx,marker){
					var m = marker.getPosition();
					
					var tLatLng = new google.maps.LatLng(m.lat(),m.lng());
					markerBounds.extend(tLatLng);
				});
			}
		});

		
		map.fitBounds(markerBounds);
		
		
		index++;
		poly[index].setPaths(new google.maps.MVCArray([path[index]]));
		
	}
	

}
function autocompleteBox(){
	var input = (document.getElementById('pac-input'));
	var types = document.getElementById('type-selector');
	var bar = document.getElementById('bar');
	var bar1 = document.getElementById('bar1');
	var bar2 = document.getElementById('bar2');
	map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
	map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
	map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(bar);
	map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(bar1);
	map.controls[google.maps.ControlPosition.TOP_LEFT].push(bar2);


	var autocomplete = new google.maps.places.Autocomplete(input);
	autocomplete.bindTo('bounds', map);
	
	
	
	google.maps.event.addListener(autocomplete, 'place_changed', function() {
		var place = autocomplete.getPlace();
		
		if (!place.geometry) {
			return;
		}
		
		objMap.lat = place.geometry.location.lat();
		objMap.lng = place.geometry.location.lng();
		objMap.center = new google.maps.LatLng(objMap.lat, objMap.lng);
		if (place.geometry.viewport) {
			map.fitBounds(place.geometry.viewport);
		} else {
			map.setCenter(place.geometry.location);
			map.setZoom(objMap.zoom);
		}
	});
	
	

}

function polygonChanged(event) {
	console.log(event);
}
function addPoint(event,draw,_case) {


	if(draw){
		if(typeof event.latLng == "undefined"){
			try{
				path[index].insertAt(path[index].length, event );
			}catch(ee){
				console.log(ee.message);
			}
		}else{
			try{
				path[index].insertAt(path[index].length, event.latLng);
			}catch(ee){
				console.log(ee.message);
			}
		}
		
		var marker = new google.maps.Marker({
			position: event,
			map: map,
			draggable: true
		});
		
		switch(_case){
			case "TH1":
				areaList(event.lat(),event.lng());
			break;
			default:
				areaList(event.lat,event.lng);
			break;
		}
		
	}else{
		path[index].insertAt(path[index].length, event.latLng);

		var marker = new google.maps.Marker({
			position: event.latLng,
			map: map,
			draggable: true
		});
		areaList(event.latLng.lat(),event.latLng.lng());
	}
	
	marker.setTitle("#" + path.length);
	addMarkerToPolygon(marker,true);
	
	if(!showMarker){
		marker.setMap(null);
	}
		
	
	
    
}
function addMarkerToPolygon(marker,nopush){
	
	if(!nopush){
	
	}else{
		markers[index].push(marker);
	}
	
	google.maps.event.addListener(marker, 'dblclick', function (event) {

		var tmpII = [];
		$.each(markers,function(i,marker){
			if(marker.length!=0){
				$.each(marker,function(ii,m){					
					if( (event.latLng.lat() == m.getPosition().lat() ) && ( event.latLng.lng() == m.getPosition().lng() )){
						
						m.setMap(null);
						tmpII.push({i:i,ii:ii});

					}
					
				});
			}
		});
		$.each(tmpII,function(i,y){
			markers[y.i].splice(y.ii, 1);
			positions[y.i].splice(y.ii, 1);
			path[y.i].removeAt(y.ii);
		});
		tmpII = [];

		updatePosition();
	});
	console.log('added Marker')
	google.maps.event.addListener(marker, 'dragstart', function (event) {
		dragMarkerStart = event;
		
		
	});
	google.maps.event.addListener(marker, 'dragend', function (event) {

		// if(!multiple){
		
			for (var i = 0, I = markers[index].length; i < I && markers[index][i] != marker; ++i);
			path[index].setAt(i, marker.getPosition());
			updateList(marker,i,index);	
			
			return false;
		
		// }

		
		/*var tmpII = [];
		
		$.each(markers,function(i,marker){
			if(marker.length!=0 && typeof marker.length == "number"){
				$.each(marker,function(ii,m){		
					
					if( (parseFloat(dragMarkerStart.latLng.lat()) == parseFloat(m.getPosition().lat()) ) 
						&& ( parseFloat(dragMarkerStart.latLng.lng()) == parseFloat(m.getPosition().lng()) )){
						var mm =  new google.maps.Marker({
							position: new google.maps.LatLng(parseFloat(event.latLng.lat()), parseFloat(event.latLng.lng())),
							map: map,
							draggable: true
						});
						tmpII.push({i:i,ii:ii,m:mm});

					}
					
				});
			}
		});
		
		console.log(tmpII.length)
		$.each(tmpII,function(i,y){
			
			path[y.i].setAt(y.ii, y.m.getPosition());
			
			updateList(y.m,y.ii,y.i)
		});
		
		*/
		
		dragMarkerStart = null;
	});
}

function drawCoordinates() {

    path[index] = poly[index].getPath();
    0 < path[index].length && (marker = new google.maps.Marker({
        position: path[index][path[index].length - 1],
        map: map
    }));
    poly[index] && poly[index].setMap(map);
    var a = google.maps.geometry.spherical.computeArea(path[index]),
        b = a / 1E6,
        d = 3.86102159E-7 * a,
        c = 2.47105381E-4 * a,
        e = 10.7639104 * a;
	
    var area = "" + a.toFixed(0) + " meters<sup>2</sup><br> " + e.toFixed(0) + " feet<sup>2</sup> <br>" + c.toFixed(2) + " acres <br>" + d.toFixed(3) + " miles<sup>2</sup> " + b.toFixed(3) + " km<sup>2</sup><br>";
	$("#status").html(area);
	
	
    
}
function updatePosition(){
	saveCoordinates();
}
function updateList(marker,i,idex){
	
	var lat = marker.position.lat();
	var lng = marker.position.lng();
	var area = $(".area li");
	
	drawCoordinates();
	
	
	positions[idex][i]['lat'] = lat;
	positions[idex][i]['lng'] = lng;
	
	
	markers[idex][i]['lat'] = lat;
	markers[idex][i]['lng'] = lng;
	
	

	drawDistance();
	UpdateCoordinates(idex);

}
function areaList(lat,lng){
	drawCoordinates();
	positions[index].push({lat:lat,lng:lng,area_id:index});
	drawDistance();
	saveCoordinates();

}
var rad = function(x) {
	return x * Math.PI / 180;
};

function getDistance(p1, p2){
	var R = 6378137; // Earth’s mean radius in meter
	var dLat = rad(p2.lat - p1.lat);
	var dLong = rad(p2.lng - p1.lng);
	var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(rad(p1.lat)) * Math.cos(rad(p2.lat)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	var d = R * c;
	return d; // returns the distance in meter
}
function drawDistance(){
	var statusPerimeter = $("#statusPerimeter");
	if(positions[index].length<3){
		statusPerimeter.html(" "+0+" meters<sup>2</sup> <br> 0 km<sup>2</sup> ");
		return false;
	
	}
	positionsMVC = [];
	for(var x = 0;x<positions[index].length;x++){
		
		var t = x+1;
		if(typeof positions[index][t] == "undefined"){
			positionsMVC.push({
				0:positions[index][x],
				1:positions[index][0]
			});
		}else{
			positionsMVC.push({
				0:positions[index][x],
				1:positions[index][t]
			});
		}
		
		
	}
	var Perimeter = 0;
	for(var x = 0;x<positionsMVC.length;x++){
		var t = parseFloat(getDistance(positionsMVC[x][0],positionsMVC[x][1]));
		Perimeter = Perimeter + t;
	}
	statusPerimeter.html(" "+Perimeter+" meters<sup>2</sup> <br> "+(Perimeter/1000)+" km<sup>2</sup>");

}
function disablePolyAndMarker(i){
	poly[i].setOptions({ editable: false});
	$.each(markers[i],function(x,y){
		y.setMap(null);
		
	});
}
$().ready(function(e){
	$(".save").click(function(e){
		objMap.center = new google.maps.LatLng(objMap.lat+ ((Math.random() - 0.5) / 100), objMap.lng + ((Math.random() - 0.5) / 100));
		map.panTo(objMap.center);
		/** ADD NEW MARKER **/
		if(positions[index].length!=0){
			
			disablePolyAndMarker(index);
			index++;
		
		}
		path[index] = new google.maps.MVCArray;
		poly[index] = new google.maps.Polygon({
			strokeWeight: 3,
			editable:true,
			fillColor: 'green',
			fillOpacity: 0.4,
			strokeColor: 'red',
			strokeOpacity: 1,
			strokeWeight: 3,
			zIndex: 1,
			editable: true,
		});
		poly[index].setMap(map);
		poly[index].setPaths(new google.maps.MVCArray([path[index]]));
		
		

		addPoint(objMap.center,true,"TH1");
		
		saveCoordinates();
		
		
		
	});
	$(".deleteMarkers").click(function(e){
		$.each(markers,function(i,marker){
			if(marker.length!=0){
				$.each(marker,function(ii,m){					
					m.setMap(null);
				});
			}
			path[i] = new google.maps.MVCArray();
			poly[i].setPaths(new google.maps.MVCArray([path[i]]));
			markers[i] = [];
			
		});

			
		


		resetMap();
		$.post("delete.php",{},function(res){
		
		});
	});
	$(".delete").click(function(e){
		var lat = $(this).attr('lat');
		var lng = $(this).attr('lng');
		var cnt = $(this).attr('cnt');
	});
	$(".deleteLastMarkers").click(function(e){
		var i = markers[index].length-1;
		if(i>=0){
			try{
				markers[index][i].setMap(null);
				markers[index].splice(i, 1);
				path[index].removeAt(i);
			}catch(e){
				console.log(e.message);
			}
		}
	});
	
	$(".markerBounds").click(function(e){
		if(positions[index].length == 0) return false;
		$.each(positions[index],function(x,marker){
			var tLatLng = new google.maps.LatLng( marker.lat, marker.lng);
			markerBounds.extend(tLatLng);
		});
		map.fitBounds(markerBounds);
	});
	$(".border_color button").click(function(e){
		var color = $(this).attr('color');
		poly[index].setOptions({ strokeColor: color});
	});
	$(".color_fill button").click(function(e){
		var color = $(this).attr('color');
		poly[index].setOptions({ fillColor: color});
	});
	$(".show_border button").click(function(e){
		var border = $(this).attr('border');
		if(border == "yes"){
			poly[index].setOptions({ strokeWeight: 3});
		}else{
			poly[index].setOptions({ strokeWeight: 0});
		}
	});
	
	$(".show_markers button").click(function(e){
		var show = $(this).attr('show');
		if(show == "yes"){
			showMarker = true;
			$.each(markers[index],function(x,marker){
				marker.setMap(map);
			});
		}else{
			showMarker = false;
			$.each(markers[index],function(x,marker){
				marker.setMap(null);
			});
		}
	});
	$(".currentLocation").click(function(e){
		
		if(navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(position) {
				var pos = new google.maps.LatLng(position.coords.latitude,
					position.coords.longitude);

				
				map.setCenter(pos);
			}, function(e) {
				console.log(e)
				handleNoGeolocation(true);
			});
		} else {
			// Browser doesn't support Geolocation
			handleNoGeolocation(false);
		}
	});
	$(".point").live('click',function(e){
		var lat = $(this).attr('lat');
		var lng = $(this).attr('lng');
		map.panTo(new google.maps.LatLng(lat,lng));
		map.setZoom(16);
	});
	$(".delete").live('click',function(e){
		var i = $(this).attr('index');
		$(this).parent().parent().remove();
		
		$.each(markers[i],function(ii,marker){
			console.log(marker)
			marker.setMap(null);
			

			
		});
		path[i] = new google.maps.MVCArray();
		poly[i].setPaths(new google.maps.MVCArray([path[i]]));
		markers[i] = [];
			
		


		
		$.post("deleteArea.php",{i:i},function(res){
		
		});
	});
	
	
});
function handleNoGeolocation(errorFlag) {
	if (errorFlag) {
		var content = 'Error: The Geolocation service failed.';
	} else {
		var content = 'Error: Your browser doesn\'t support geolocation.';
	}

	var options = {
		map: map,
		position: objMap.center,
		content: content
	};
	alert(options.content)
	

}
function drawTables(){
	var html = "";
	$.each(positions,function(x,y){
		if(y.length!=0){
			html+='<tr>';
			var d = new Date();
			var m = parseInt(d.getMonth()+1);
			var i =x + 1;
			if(m<10) m = "0"+m;
			var dt = d.getFullYear() +"-"+ m  +"-"+ d.getDate() + " "+ d.getHours() +":"+ d.getMinutes()+":"+d.getSeconds();
			html+='<tr><td>'+i+'</td><td>'+dt+'</td><td>'
			var inder = 0;
			$.each(y,function(xx,yy){
				
				
				
				
				
				html+='<p><a href="javascript:void(0)" class="point" lat="'+yy.lat+'" lng="'+yy.lng+'">';
				html+='('+yy.lat+' , '+yy.lng+')';
				html+='</p>';
				inder = yy.area_id;
				
				
			});
			html+='</td><td><a index="'+inder+'" class="delete" href="javascript:void(0)">Delete</a></td>';
			html+='</tr>';
		}
	});
	$('.table tbody').html(html);
}
function saveCoordinates(){
	drawTables();
	var post  = {data:positions[index],area:index};
	$.post("save.php",post,function(res){
		
	});
}
function UpdateCoordinates(idex){
	drawTables();
	var post  = {data:positions[idex],area:idex};
	$.post("save.php",post,function(res){
		
	});
}
function DEBUG(){
	console.log("-- POLY --");
	console.log(poly);
	console.log("-- PATH --");
	console.log(path);
	console.log("-- POSITIONS --");
	console.log(positions);
	console.log("-- MARKERS --");
	console.log(markers);
	
}
getCoordinates();

function getCoordinates(loadInit){
	
	$.post("get.php",{},function(res){
		
		var inder = 0;
		var length = 0;
		$.each(res,function(x,areas){
			var tmpll = [];
			var tmpLatLng = [];
			var tmpMarker = [];
			$.each(areas,function(x,marker){
				var ll = new google.maps.LatLng(parseFloat(marker.latitude), parseFloat(marker.longtitude));
				tmpll.push({lat:parseFloat(marker.latitude),lng:parseFloat(marker.longtitude),area_id:marker.area_id})
				tmpLatLng.push(ll);
				var mm =  new google.maps.Marker({
					position: ll,
					map: map,
					draggable: true
				});
				tmpMarker.push(mm);
				inder = parseInt(marker.area_id);
			});
			
			positions[x] = tmpll;
			markers[x] = tmpMarker;
			path[x] = new google.maps.MVCArray(tmpLatLng);
			length++;
			
		});
		
		
		index = inder;
		drawTables();
		if(length == 0){
			multiple = false;
			initialize();
		}else{
			multiple = true;
			initialize();
			
			
		}
		
		
	});
}




/** google.maps.event.addDomListener(window, 'load', initialize); **/